package com.levy.utils.FileTool;

import cn.hutool.core.util.HexUtil;

import java.io.*;

/**
 * 16进制文件读取与写入
 * Created by levy on 2019/6/21.
 */
public class HexFileUtils {

    /**
     * 将文件读取为16进制String
     * Read original File and transfer it into Hex String
     *
     * @return
     * @throws IOException
     */
    public static String readOriginal2HexStr(String filePath) throws IOException {
        FileInputStream fin = new FileInputStream(new File(filePath));
        StringWriter sw = new StringWriter();

        int len = 1;
        byte[] temp = new byte[len];

       /*16进制转化模块*/
        for (; (fin.read(temp, 0, len)) != -1; ) {
            if (temp[0] > 0xf && temp[0] <= 0xff) {
                sw.write(Integer.toHexString(temp[0]));
            } else if (temp[0] >= 0x0 && temp[0] <= 0xf) {
                //对于只有1位的16进制数前边补“0”
                sw.write("0" + Integer.toHexString(temp[0]));
            } else {
                //对于int<0的位转化为16进制的特殊处理，因为Java没有Unsigned int，所以这个int可能为负数
                sw.write(Integer.toHexString(temp[0]).substring(6));
            }
        }

        return sw.toString();
    }

    /**
     * 转字节数组为16进制字符串
     * @param bytes
     * @return
     */
    public static String bytes2HexStr(byte[] bytes){
        StringBuilder sb = new StringBuilder();
        if (bytes ==null || bytes.length <= 0){
            return null;
        }

        for (byte b:bytes){
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() <2){
                sb.append(0);
            }
            sb.append(hv);
        }
        return sb.toString();
    }

    /**
     * 将替换后的16进制字符串写回文件
     * write replaced original String to file
     *
     * @param hexStr
     * @throws NumberFormatException
     * @throws IOException
     */
    public static void writeNew2Binary(String hexStr, String filePath) throws NumberFormatException,
            IOException {
        FileOutputStream fout = new FileOutputStream(filePath);

        for (int i = 0; i < hexStr.length(); i = i + 2) {
            fout.write(Integer.parseInt(hexStr.substring(i, i + 2), 16));
        }

    }


    public static void main(String[] args) throws IOException {
//        String path = "G:\\xxx.class";
//        String s = readOriginal2HexStr(path);

        String testStr = "123456";
        writeNew2Binary(testStr, "G:\\1.txt");
        //获取123456的asc码
        byte[] bytes = testStr.getBytes();
        //遍历依次转换asc码
        String s = bytes2HexStr(bytes);
        //转换结果
        System.out.println(s);


//        String s = readOriginal2HexStr("G:\\1.txt");
//        byte[] bytes = HexUtil.decodeHex(s);
//        System.out.println();
//        System.out.println(s);
    }
}
